import { BaseController, $fetch } from '#server/common/index.js';

const getCommunityName = (hostname) => {
  return import.meta.env.VITE_MOCK_COMMUNITY_NAME ?? hostname.split('.').reverse()[2] ?? '';
};

class Controller extends BaseController {
  // 首页
  async main() {
    if (this.$ctx.request.originalUrl === '/sitemap.xml') {
      const community = getCommunityName(this.$ctx.request.hostname ?? '');
      const { isSuccess, data } = await $fetch('/communityFile/sitemap', {
        baseURL: import.meta.env.VITE_SERVER_BASE_URL,
        headers: {
          'X-ATOMGIT-POP-COMMUNITY': community,
        },
      });

      if (isSuccess) {
        this.$ctx.response.set({
          'Content-Type': 'application/xml',
          'Cache-Control': 'no-cache',
        });
        this.$render('server/sitemap.xml', {
          community,
          news: data?.news ?? [],
        });
      }
      else {
        this.$ctx.next();
      }
    }
    else if (this.$ctx.request.originalUrl === '/robots.txt') {
      const { isSuccess, data } = await $fetch('/communityFile/robots', {
        baseURL: import.meta.env.VITE_SERVER_BASE_URL,
        headers: {
          'X-ATOMGIT-POP-COMMUNITY': getCommunityName(this.$ctx.request.hostname ?? ''),
        },
      });

      if (isSuccess) {
        this.$ctx.response.set({
          'Content-Type': 'text/plain',
          'Cache-Control': 'no-cache',
        });
        this.$ctx.response.send(data.fileData);
      }
      else {
        this.$ctx.next();
      }
    }
    else {
      this.$ctx.next();
    }
  }
}

export default Controller;
